package com.woniuxy.kaer.user.interceptor;

import com.woniuxy.kaer.commons.jwtUtil.JwtUtil;
import com.woniuxy.kaer.redis.util.RedisKey;
import io.jsonwebtoken.Claims;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.security.auth.message.AuthException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.concurrent.TimeUnit;
@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private RabbitTemplate rabbitTemplate;
    @Resource
    private JwtUtil jwtUtil;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("请求进入拦截器");
        //排除 预检请求
        if(request.getMethod().equalsIgnoreCase("OPTIONS")){
            return true;
        }

        //取出请求头
        String accessToken = request.getHeader("token");
        if(accessToken == null ){
            throw new AuthException("身份令牌无效");
        }
        if(stringRedisTemplate.hasKey(RedisKey.ACCESS_EXPIRE(accessToken))){
            return true;
        }
        synchronized (accessToken.intern()){
            //加锁保证短token排队续期
            if(stringRedisTemplate.hasKey(RedisKey.ACCESS_EXPIRE(accessToken))){
                return true;
            }
            //判断长token是否有效
            if(stringRedisTemplate.getExpire(RedisKey.REFRESH_ACCESS_EXPIRE(accessToken), TimeUnit.SECONDS)/60>=5) {
                //取出之前的长token
                String refreshToken = stringRedisTemplate.opsForValue().get(RedisKey.REFRESH_ACCESS_EXPIRE(accessToken));
                //解析长token
                Claims claims = jwtUtil.parseToken(refreshToken);
                //取出长token的过期时间判断是否大于5分钟
                String newAccessToken = jwtUtil.createToken(claims, 3);
                String newRefreshToken = jwtUtil.createToken(claims, 3 * 24 * 60);
                //通过响应头将jwt相应给前端
                response.setHeader("token", newAccessToken);
                //在跨域访问时必须将响应头设置为允许跨域
                response.setHeader("Access-Control-Expose-Headers", "token");
                //保存新的长token和短token
                //将之前的短token延时
                //保存短token
                stringRedisTemplate.opsForValue().set(RedisKey.ACCESS_EXPIRE(newAccessToken), "", 3, TimeUnit.MINUTES);
                //保存长token
                stringRedisTemplate.opsForValue().set(RedisKey.REFRESH_ACCESS_EXPIRE(newAccessToken), newRefreshToken, 3 * 24 * 60, TimeUnit.MINUTES);
                //为短token延时，避免并发
                stringRedisTemplate.opsForValue().set(RedisKey.ACCESS_EXPIRE(accessToken), "", 1L, TimeUnit.MINUTES);
                //延时删除之前的token
                //将KEY保存到消息队列，通过延迟队列删除缓存
                rabbitTemplate.convertAndSend("", "delete-refresh-token-routing-key", RedisKey.REFRESH_ACCESS_EXPIRE(accessToken));
            }
        }
        // 判断 token 是否有效
        try {
            jwtUtil.parseToken(accessToken);
        } catch (Exception e) {
            throw new AuthException("非法身份令牌");
        }
        return true;
    }
}
